<?php
namespace app\admin\controller;

use app\admin\model\AuthGroup;
use think\Controller;
use app\admin\model\Admin;
use app\admin\model\AdminLog;
use zzcms\util\Tool;

class Common extends Controller
{

    protected function initialize()
    {
        parent::initialize();
    }


    /**
     * 登录
     * @return mixed
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $post = $this->request->param();
            $info = Admin::getInstance()->getOne(['username' => $post['username']]);
            if (empty($info)) {
                return $this->error('用户名不存在');
            }
            //把数据转换为数组
            if ($info['password'] != zzcmsPassword($post['password'], $info['password_code'])) {
                $this->error('您输入的密码不正确');
            }
            //判断管理级别
            if ($info['founder'] == 1) {
                $info['level'] = 1;
            } else {
                $info['level'] = $info['parent_id'] == 1 ? 2 : 3;
            }
            //记录登录日志
            $data = [];
            $data['admin_id'] = $info['id'];
            $data['ip'] = $this->request->ip();
            $data['system'] = Tool::getSystem();
            $data['browser'] = Tool::getBrowse();
            AdminLog::getInstance()->addData($data);
            unset($info['password']);
            $info['rule'] = $this->checkRule($info);
            session('admininfo', $info);
            return $this->success('登录成功');
        } else {
            return $this->fetch();
        }
    }

    /**
     * 退出成功
     */
    public function logout()
    {
        // 清除session（当前作用域）
        session('admininfo', null);
        $this->redirect('common/login');
    }


    /**
     * 更新用户的权限
     * @param $info
     * @return bool
     */
    public function checkRule($info)
    {
        if ($info['level'] == 2) {
            $rule = AuthGroup::getInstance()->where(['id' => $info['role_id']])->value('rules');
            return empty($rule) ? '' : $rule;
        } elseif ($info['level'] == 3) {
            //子账号信息
            $parent_info = Admin::getInstance()->getOne($info['parent_id']);
            $ids = $info['role_id'] . ',' . $parent_info['role_id'];
            $role_info = AuthGroup::getInstance()->where('id', 'in', $ids)->column('rules');
            $array1 = explode(',', $role_info[0]);
            $array2 = explode(',', $role_info[1]);
            if ($array1 == $array2) {
                return $role_info[0];
            }
            //子账号及用户交集
            $rule_array = array_intersect($array1, $array2);
            AuthGroup::getInstance()->where(['id' => $info['role_id']])->setField(['rules' => implode(',', $rule_array)]);
            return implode(',', $rule_array);
        } else {
            return '';
        }
    }
}
